package com.innovation.ic.cyz.web.interceptors;

//import com.google.gson.Gson;
//import com.innovation.ic.b1b.framework.util.JwtUtils;
//import com.innovation.ic.cyz.base.pojo.global.ApiResult;
//import com.innovation.ic.cyz.base.pojo.annotation.JwtToken;
//import com.innovation.ic.cyz.base.pojo.constant.JwtTokenType;
//import org.springframework.http.HttpStatus;
//import org.springframework.web.method.HandlerMethod;
//import org.springframework.web.servlet.HandlerInterceptor;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.lang.reflect.Method;
//import java.util.Map;

//public class JwtInterceptor implements HandlerInterceptor {

  /*  @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 获取目标方法的Method对象
        Method method = handlerMethod.getMethod();

        response.setContentType("text/json;charset=utf-8");

        // 如果目标方法没有JwtToken注解直接通过
        if (!method.isAnnotationPresent(JwtToken.class)) {
            return true;
        }

        // 目标方法有JwtToken注解

        String token = request.getHeader("authorization");
        String tokenErrMsg = "";

        Integer jwtTokenType = method.getAnnotation(JwtToken.class).type();
        if (jwtTokenType == JwtTokenType.Required) { // 注解标注：Token必须有
            if (token == null) {
                tokenErrMsg = "token为空";
            } else {
                // header中有token, 验证token有效性
                try {
                    JwtUtils.verify(token);
                    return true;
                } catch (Exception e) {
                    tokenErrMsg = "token无效";
                }
            }
        } else if (jwtTokenType == JwtTokenType.Nullable) { // 注解标注：Token可有可无
            if (token == null) {
                return true;
            } else {
                // header中有token, 验证token有效性
                try {
                    JwtUtils.verify(token);
                    return true;
                } catch (Exception e) {
                    tokenErrMsg = "token无效";
                }
            }
        }

        // 返回错误信息
        ApiResult<Map<String, Object>> apiResult = new ApiResult<>();
        apiResult.setCode(HttpStatus.UNAUTHORIZED.value());
        apiResult.setMessage(tokenErrMsg);
        apiResult.setSuccess(false);

        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(new Gson().toJson(apiResult));
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        return false;
    }*/

//}
